/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="onePageTable">
  <div class="commonTablePanel openatc-operation common-comp-chart" ref="crossFlowChart">
    <div class="common-table-header" style="display:inline-block;width:100%;">
      <div class="common-table-title-container">
        <div class="common-table-title">
          <i class="iconfont icon-shebeiguzhangtongji"></i>
          <span>{{$t('openatc.devicefault.devicefailurestatistics')}}</span>
          <span class="separator">|</span>
        </div>
      </div>
      <div class="filter-container" id="queryingCompFilters">
        <div class="filters">
            <span class="header-span">{{$t('openatc.devicefault.roadname') }}：</span>
            <SelectAgentid ref="selectAgentid" @onChange="onChangeAgentid"></SelectAgentid>
        </div>
        <div class="filters">
            <span class="header-span">{{$t('openatc.devicefault.cardtype') }}：</span>
            <el-select
            v-model="cardtype"
            clearable
            style="width: 120px;"
            filterable>
            <el-option
                v-for="(item, index) in boardTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filters">
            <span class="header-span">{{$t('openatc.devicefault.faulttype') }}：</span>
            <el-select
            v-model="faulttype"
            style="width: 120px;"
            clearable
            @change="changeType"
            filterable>
            <el-option
                v-for="(item, index) in mainFaultOptions"
                :key="index"
                :label="item.value"
                :value="item.label"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filters">
            <span class="header-span">{{$t('openatc.faultrecord.faultchild') }}：</span>
            <el-select
            v-model="faultchild"
            style="width: 120px;"
            clearable
            filterable>
            <el-option
                v-for="(item, index) in faultchilds"
                :key="index"
                :label="item.value"
                :value="item.label"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filters">
            <span class="header-span">{{$t('openatc.devicefault.level') }}：</span>
            <el-select
            v-model="level"
            style="width: 120px;"
            clearable
            filterable>
            <el-option
                v-for="(item, index) in levels"
                :key="index"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filters" style="border:0px solid red;">
            <span class="header-span">{{$t('openatc.operation.interval') }}：</span>
            <el-select
            v-model="interval"
            style="width: 120px;"
            clearable
            filterable>
            <el-option
                v-for="(item, index) in intervalList"
                :key="index"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </div>
        <div class="filters timepicker">
          <span class="header-span">{{$t('openatc.operation.time') }}：</span>
          <template>
            <el-date-picker
                style="width: 280px;"
                popper-class="common-date-popper"
                v-model="timeValue"
                align="center"
                type="daterange"
                :start-placeholder="$t('openatc.usermanager.starttime')"
                :end-placeholder="$t('openatc.usermanager.endtime')">
            </el-date-picker>
          </template>
        </div>
        <div class="filters">
            <el-button type="primary" class="add-btn" icon="el-icon-search" @click="handleFilters"></el-button>
        </div>
        <div class="filters">
            <el-dropdown trigger="click" @command="handleCommand">
                <el-button type="primary">
                    {{$t('openatc.operation.export')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" style="width: 110px">
                    <el-dropdown-item command="exportCSV" style="line-height: 32px;text-align: center;">
                        csv
                    </el-dropdown-item>
                    <el-dropdown-item command="exportHTML" style="line-height: 32px;text-align: center;">
                        html
                    </el-dropdown-item>
                    <el-dropdown-item command="exportPDF" style="line-height: 32px;text-align: center;">
                        pdf
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
          </div>
      </div>
    </div>
    <!-- <div class="tittle">{{$t('openatc.devicefault.devicefailurestatistics')}}</div> -->
    <!-- <CompFilters showCycle id="queryingCompFilters" @handlefilters="handleAddCompareLine" @handleExportPDF="handleExportPDF" @handleExportHTML="handleExportHTML" @handleExportCSV="handleExportCSV" /> -->
    <!-- <CompFiltersTags :filterTags="filterTags" @handleCloseTag="handleCloseTag" /> -->
    <!-- <div class="analysis-charts"> -->
    <div class="charts" id="crossflow"></div>
    <!-- </div> -->
  </div>
</div>
</template>

<script>
import * as echart from 'echarts'
import { getTheme } from '../../utils/auth'
import { getFault } from '../../api/device'
import moment from 'moment'
import { downloadPDF } from '../../utils/exportHtmlToPdf.js'
import { ExportEchartsHtml } from '../../utils/exportChartsToHtml.js'
import { ExportHistoricalStatistics } from '../../utils/exportExcel.js'
import { getMessageByCode } from '../../utils/responseMessage'
import SelectAgentid from '../../components/SelectAgentid'
import { getBoardType, getAllMainFaultTypeArr, getFaultChildren } from '../../utils/fault.js'
export default {
  components: {
    SelectAgentid
  },
  data () {
    return {
      timeValue: this.getDefaultDate(),
      faulttype: '',
      level: '',
      agentid: '',
      levels: [
        {
          label: this.$t('openatc.faultrecord.general'),
          value: '1'
        },
        {
          label: this.$t('openatc.faultrecord.degradation'),
          value: '2'
        },
        {
          label: this.$t('openatc.faultrecord.serious'),
          value: '3'
        }
      ],
      faultchild: '',
      faultchilds: [],
      mainFaultOptions: [],
      boardTypeOptions: [],
      cardtype: '',
      intervalList: [
        {
          label: this.$t('openatc.operation.day'),
          value: 'day'
        },
        {
          label: this.$t('openatc.operation.hour'),
          value: 'hour'
        }
      ],
      interval: '',
      loading: false,
      allLineData: [], // 当前所有曲线数据
      allCharts: [], // 折线图所需数据
      legends: [],
      csvData: new Map()
    }
  },
  created () {
    // this.getDeviceRanges()
    // this.getList()
    this.initOptions()
  },
  methods: {
    changeType (val) {
      this.faultchild = ''
      this.faultchilds = getFaultChildren(val, this.$i18n)
    },
    handleCommand (command) {
      switch (command) {
        case 'exportCSV': this.handleExportCSV()
          break
        case 'exportHTML': this.handleExportHTML()
          break
        case 'exportPDF': this.handleExportPDF()
          break
        default: console.log('no command!')
      }
    },
    onChangeAgentid (agentid) {
      this.agentid = agentid
    },
    initOptions () {
      this.boardTypeOptions = getBoardType(this.$i18n)
      this.mainFaultOptions = getAllMainFaultTypeArr(undefined, undefined, this.$i18n)
    },
    handleFilters () {
      if (this.agentid === '') {
        this.$message({
          message: this.$t('openatc.devicefault.roadnameempty'),
          type: 'warning'
        })
        return
      }
      if (this.cardtype === '') {
        this.$message({
          message: this.$t('openatc.devicefault.cardtypeempty'),
          type: 'warning'
        })
        return
      }
      if (this.faulttype === '') {
        this.$message({
          message: this.$t('openatc.devicefault.faulttypeempty'),
          type: 'warning'
        })
        return
      }
      // if (this.faultchild === '') {
      //   this.$message({
      //     message: this.$t('openatc.devicefault.faultchildempty'),
      //     type: 'warning'
      //   })
      //   return
      // }
      if (this.level === '') {
        this.$message({
          message: this.$t('openatc.devicefault.levelempty'),
          type: 'warning'
        })
        return
      }
      if (this.timeValue === null) {
        this.$message({
          message: this.$t('openatc.operation.timeempty'),
          type: 'warning'
        })
        return
      }
      if (this.interval === '') {
        this.$message({
          message: this.$t('openatc.operation.intervalempty'),
          type: 'warning'
        })
        return
      }
      this.refreshChart()
    },
    getRouteFlow () {
      let reqData = {
        'agentId': this.agentid,
        'm_byFaultBoardType': this.cardtype,
        'm_wFaultType': this.faulttype,
        'm_byFaultLevel': this.level,
        'intervalType': this.interval
      }
      if (this.faultchild !== undefined && this.faultchild !== '') {
        reqData.m_wSubFaultType = this.faultchild
      }
      if (this.timeValue !== null) {
        let beginTime = moment(this.timeValue[0]).format('YYYY-MM-DD') + ' 00:00:00'
        let endTime = moment(this.timeValue[1]).format('YYYY-MM-DD') + ' 23:59:59'
        reqData.beginTime = beginTime
        reqData.endTime = endTime
      }
      return new Promise((resolve, reject) => {
        getFault(reqData).then((res) => {
        //   this.legends = []
          if (!res.data.success) {
            this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
            return
          }
          let phaseStatic = res.data.data
          resolve(phaseStatic)
        })
      })
    },
    lockScreen () {
      this.loading = true
    },
    unlockScreen () {
      this.loading = false
    },
    getDefaultDate () {
      let end = new Date()
      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]
    },
    initChart () {
      this.crosssChart = echart.init(document.getElementById('crossflow'))
      const _this = this
      window.onresize = function () {
        _this.crosssChart.resize()
      }
    },

    refreshStrengthChart () {
      return this.getRouteFlow().then(data => {
        this.curAddcrosssData = JSON.parse(JSON.stringify(data))
        this.csvData.clear()
        this.csvData.set(this.$t('openatc.devicefault.count'), this.curAddcrosssData)
        this.allLineData = this.curAddcrosssData
        this.getStrSeries(this.allLineData)
        this.crosssChart.clear()
        this.renderStrengthChart()
      })
    },
    renderStrengthChart () {
      if (this.allCharts.length === 0) {
        this.crosssChart.clear()
        return
      }
      // 渲染
      let strOption = this.getStrOption()
      this.crosssChart.setOption(strOption, true)
      this.crosssChart.resize()
    },
    // 渲染
    getStrOption () {
      let strOption = {
        tooltip: {
          trigger: 'axis'
        },
        // title: {
        //   text: `${(this.controlTypes === '201' ? this.$t('openatccomponents.overview.controlType' + this.controlTypes) : this.$t('openatccomponents.overview.modelList' + this.controlTypes)) + this.$t('openatc.operation.total') + this.allCharts[0].total}`,
        //   // text: `${this.$t('openatc.operation.total') + this.allCharts[0].total}`,
        //   x: 'center',
        //   textStyle: {
        //     color: getTheme() === 'light' ? '#666666' : '#B9BABF'
        //   }
        // },
        // legend: {
        //   bottom: 60,
        //   textStyle: {
        //     color: getTheme() === 'light' ? '#666666' : '#B9BABF'
        //   },
        //   data: this.allCharts.length > 0 ? [this.allCharts[0].name] : []
        // },
        grid: {
          containLabel: true,
          height: '80%',
          width: '98%',
          right: '20',
          left: '20',
          bottom: '80'
        },
        toolbox: {
          right: '10%',
          top: '10%',
          feature: {
            saveAsImage: {
              name: this.$t('openatc.devicefault.devicefailurestatistics'),
              title: this.$t('openatc.operation.savepng')
            }
          }
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: true,
            axisLabel: {
              rotate: '8',
              margin: 20,
              align: 'center',
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            },
            axisTick: {
              show: true,
              length: 6,
              alignWithLabel: true,
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            data: this.allCharts.length > 0 ? this.allCharts[0].time : []
          }
        ],
        yAxis: [
          {
            type: 'value',
            // name: this.allCharts.length > 0 ? this.allCharts[0].name : '',
            axisTick: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            axisLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#D7DFE1' : '#30384D'
              }
            },
            splitLine: {
              lineStyle: {
                color: getTheme() === 'light' ? '#DCDFE6' : '#30384d'
              }
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: getTheme() === 'light' ? ['#fafafa', '#fff'] : ['#202940', '#1a2338']
              }
            },
            axisLabel: {
              textStyle: {
                color: getTheme() === 'light' ? '#666666' : '#B9BABF'
              }
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100
          }
        ],
        series: [...this.allCharts]
      }
      return strOption
    //   this.crosssChart.setOption(this.strOption, true)
    },
    getControlTypeval (val) {
      if (val !== undefined) {
        return this.controlType.filter(ele => Number(ele.value) === val)[0].label
      }
      return ''
    },
    getStrSeries (datas) {
      let seriesBar = {
        type: 'line',
        time: datas.map(item => item.time),
        data: datas.map(item => item.count)
      }
      this.allCharts = [seriesBar]
    },
    async refreshChart () {
      this.lockScreen()
      this.refreshStrengthChart()
      this.unlockScreen()
    },
    handleExportPDF () {
      // 导出PDF
      // 暂时让筛选项隐藏，因为html2canvas不支持css3样式
      let filterDiv = document.getElementById('queryingCompFilters')
      filterDiv.style.display = 'none'
      downloadPDF(this.$refs.crossFlowChart, this.$t('openatc.devicefault.devicefailurestatistics'))
      // 导出pdf后，再让筛选项显示
      filterDiv.style.display = 'block'
    },
    handleExportHTML () {
      let strOption = this.getStrOption()
      let echartsOptions = JSON.parse(JSON.stringify(strOption))
      echartsOptions.tooltip.extraCssText = 'min-height:200px;'
      let params = {
        echartsOptions,
        htmlname: this.$t('openatc.devicefault.devicefailurestatistics'),
        tmpTitle: this.$t('openatc.devicefault.devicefailurestatistics'),
        // filterTagsStr: this.getTagStr(),
        bgColor: getTheme() === 'light' ? '#F5F7FA' : '#191F34',
        tittleColor: getTheme() === 'light' ? '#303133' : '#fff',
        tagBgColor: getTheme() === 'light' ? '#ecf5ff' : '#233553',
        tagBorderColor: getTheme() === 'light' ? '#d9ecff' : '#264066'
      }
      ExportEchartsHtml(params)
    },
    handleExportCSV () {
      let exportdata = new Map()
      for (let [key, val] of this.csvData) {
        for (let data of val) {
          let time = data.time
          if (exportdata.has(time)) {
            let param = {
              key,
              value: (data.count || data.count === 0) ? (data.count || 0) : data.count
            }
            let mapdata = exportdata.get(time)
            mapdata.push(param)
            exportdata.set(time, mapdata)
          } else {
            let param = {
              key,
              value: (data.count || data.count === 0) ? (data.count || 0) : data.count
            }
            exportdata.set(time, [param])
          }
        }
      }
      let exportarr = []
      if (exportdata.size > 0) {
        for (let [key, val] of exportdata) {
          let exportfield = {
            '时间': key
          }
          for (let j = 0; j < val.length; j++) {
            let cur = val[j]
            exportfield[`${cur.key}`] = cur.value
          }
          exportarr.push(exportfield)
        }
        ExportHistoricalStatistics(exportarr, this.$t('openatc.devicefault.devicefailurestatistics'), [])
      }
    }

  },
  mounted () {
    let _this = this
    _this.$nextTick(function () {
      _this.initChart()
    })
  }
}

</script>

<style>

</style>
